package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.UserHolder;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.FollowUser;
import com.tanhua.mongo.Video;
import com.tanhua.template.OssTemplate;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "video")  //pageBean 放入redis中的资源必须实现序列化
    public PageBeanVo findVideo(Integer page, Integer pagesize) {

        System.out.println("我执行了...");
        //分页查询所有小视频
        PageBeanVo pageBean=videoApi.findVideo(page,pagesize);
        List<Video> items = (List<Video>) pageBean.getItems();

        ArrayList<VideoVo> voList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Video video : items) {
                // 查询userInfo
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(userInfo,vo);
                vo.setUserId(userInfo.getId());

                BeanUtils.copyProperties(video,vo);
                vo.setSignature(video.getText());
                vo.setCover(video.getPicUrl());
                vo.setVideoUrl(video.getVideoUrl());
                // 下去如果点赞 这里要从redis中获取
                vo.setHasLiked(0);
                if(stringRedisTemplate.hasKey(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), video.getUserId()))){
                    vo.setHasFocus(1);
                }else{
                    vo.setHasFocus(0);
                }
                voList.add(vo);
            }
        }
        pageBean.setItems(voList);
        //组装vo返回
        return pageBean;

    }

    @CacheEvict(value = "video",allEntries = true) //增 删 改的任何动作 都会去redis清除一个video的key
    public ResponseEntity saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        // 将封装图片上传到oss（记录地址）
        String fm_url = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        // 将视频上传到fastdfs（记录地址）
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String video_url=webServer.getWebServerUrl()+storePath.getFullPath();
        // 创建video设置属性
        Video video = new Video();
        video.setUserId(UserHolder.getUser().getId());
        video.setPicUrl(fm_url);
        video.setVideoUrl(video_url);
        video.setText("震惊~一男子半夜..");
        // 实现数据插入
        videoApi.save(video);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity guanzhu(Long followUserId) {

        FollowUser followUser = new FollowUser();
        followUser.setCreated(System.currentTimeMillis());
        followUser.setUserId(UserHolder.getUser().getId());
        followUser.setFollowUserId(followUserId);

        videoApi.guanzhu(followUser);

        //redis中
        stringRedisTemplate.opsForValue().set(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), followUserId), "1");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity unguanzhu(Long followUserId) {

        videoApi.unguanzhu(followUserId,UserHolder.getUser().getId());

        stringRedisTemplate.delete(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), followUserId));
        return ResponseEntity.ok(null);
    }
}
